package com.hepinghospital.user.ui.activity.userinfo;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.ui.JiuzhenCodeActivity;
import com.hepinghospital.user.ui.PayActivity;
import com.hepinghospital.user.ui.activity.graphic.dialog.MedicalRecordsDialog;
import com.hepinghospital.user.ui.dialog.ApplyPermissionDialog;
import com.hepinghospital.user.ui.dialog.ChooseDialog;
import com.hepinghospital.user.ui.dialog.CodeChangeDialog;
import com.hepinghospital.user.ui.dialog.CodeDialog;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.Doctor;
import com.rest.response.MyFamilyListResponse;
import com.rest.response.YSGCardInfoResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UIConstants;

/**
 * @author HP
 * @date 2020/2/20
 */

public class MyFamilyActivity extends BaseActivity {

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    MyAdapter adapter;

    private MyFamilyListResponse myFamily;
    private ChooseDialog mChooseDialog;

    List<MyFamilyListResponse> list = new ArrayList<>();
    private CodeChangeDialog mChangeCodeDialog;

    private int type;
    private Doctor doctor;

    @Override
    protected void initViews() {
        LinearLayoutManager manager = new LinearLayoutManager(MyFamilyActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> getFamilyList());
    }

    @Override
    protected void initData() {
        type = getIntent().getIntExtra("type", -1);
        doctor = (Doctor) getIntent().getSerializableExtra(UIConstants.OBJ_Doctor);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getFamilyList();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_my_family;
    }


    @OnClick(R.id.btn_add_family)
    void btn_add_family() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("2", true);
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {
            @Override
            public void onConfirm() {
                startActivity(AddMyFamilyActivity.class);
            }

            @Override
            public void onCancel() {

            }
        });
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(MyFamilyActivity.this).inflate(R.layout.item_family, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                myFamily = list.get(position);
                if (list.get(position).isBindingCard == 0) {
                    //未绑卡，先去绑卡
                    showChooseDialog();
                } else if (list.get(position).isBindingCard == 1) {
                    switch (type) {
                        case UIConstants.INTO_MyFamilyActivity_FLAG_1: {
                            //type==1是从我的页面进来的，不跳转
                            break;
                        }
                        case UIConstants.INTO_MyFamilyActivity_FLAG_2: {
                            MedicalRecordsDialog medicalRecordsDialog = MedicalRecordsDialog.Companion.getInstance();
                            medicalRecordsDialog.show(getSupportFragmentManager(), "MedicalRecordsDialog");
                            break;
                        }
                        default: {
                            Intent mIntent = new Intent();
                            mIntent.putExtra(UIConstants.OBJ_MyFamilyListResponse, list.get(position));
                            setResult(RESULT_OK, mIntent);
                            finish();
                            break;
                        }
                    }
                }
            });
            holder.tv_bind.setOnClickListener(v -> {
                myFamily = list.get(position);
                showChooseDialog();
            });
            holder.tv_relation.setText(list.get(position).relation);
            if (TextUtils.isEmpty(list.get(position).relation)) {
                holder.tv_relation.setVisibility(View.GONE);
            } else {
                holder.tv_relation.setVisibility(View.VISIBLE);

            }
            holder.tv_name.setText(list.get(position).name);
            holder.tv_phone.setText(list.get(position).phone);
            if (list.get(position).isBindingCard == 0) {
                holder.tv_bind.setVisibility(View.VISIBLE);
                holder.tv_unbind.setVisibility(View.VISIBLE);
//                holder.tv_card_num.setVisibility(View.GONE);
                holder.tv_type.setVisibility(View.GONE);
                holder.tv_type.setText("未绑卡");
                holder.iv_qrcode.setVisibility(View.GONE);
                holder.tv_type.setTextColor(ContextCompat.getColor(mContext, R.color.color_F54C4C));
            } else if (list.get(position).isBindingCard == 2) {
                holder.tv_bind.setVisibility(View.GONE);
                holder.tv_unbind.setVisibility(View.GONE);
//                holder.tv_card_num.setVisibility(View.VISIBLE);
                holder.tv_type.setVisibility(View.GONE);
                holder.tv_type.setText("审核中");
                holder.iv_qrcode.setVisibility(View.GONE);
                holder.tv_type.setTextColor(ContextCompat.getColor(mContext, R.color.commonGrey));
            } else if (list.get(position).isBindingCard == 1) {
                holder.tv_bind.setVisibility(View.GONE);
                holder.tv_unbind.setVisibility(View.GONE);
//                holder.tv_card_num.setVisibility(View.VISIBLE);
                holder.iv_qrcode.setVisibility(View.VISIBLE);
                holder.tv_type.setVisibility(View.VISIBLE);
                holder.tv_type.setTextColor(ContextCompat.getColor(mContext, R.color.commonGrey));
                if (list.get(position).cardType == 1) {
                    holder.tv_type.setText("自费就诊卡");
                } else if (list.get(position).cardType == 2) {
                    holder.tv_type.setText("医保就诊卡");
                } else if (list.get(position).cardType == 3) {
                    holder.tv_type.setText("自费卡 医保卡");
                }
            }
            holder.btn_edt.setOnClickListener(v -> {
                ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("2", true);
                applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
                applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

                    @Override
                    public void onConfirm() {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(UIConstants.OBJ_MyFamilyListResponse, list.get(position));
                        startActivity(AddMyFamilyActivity.class, bundle);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
            });
            holder.iv_qrcode.setOnClickListener(v -> {
                Intent intent = new Intent(mContext, JiuzhenCodeActivity.class);
                intent.putExtra("patientName", list.get(position).name);
                intent.putExtra("cardNo", list.get(position).ownExpenseNum);
                startActivity(intent);
            });
//            ImageLoaderHelper.getInstance().GlideImageLoader(MyFamilyActivity.this, list.get(position).);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_phone, tv_type, tv_bind, tv_relation, tv_card_num, tv_unbind;
            ImageView btn_edt, iv_head, iv_qrcode;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_phone = itemView.findViewById(R.id.tv_phone);
                tv_type = itemView.findViewById(R.id.tv_type);
                btn_edt = itemView.findViewById(R.id.btn_edt);
                tv_bind = itemView.findViewById(R.id.tv_bind);
                iv_head = itemView.findViewById(R.id.iv_head);
                tv_relation = itemView.findViewById(R.id.tv_relation);
                tv_card_num = itemView.findViewById(R.id.tv_card_num);
                tv_unbind = itemView.findViewById(R.id.tv_unbind);
                iv_qrcode = itemView.findViewById(R.id.iv_qrcode);
            }
        }
    }


    private void getFamilyList() {
        RestProxy.getInstance().getMyFamily(BaseApplication.currentUserId, new Observer<List<MyFamilyListResponse>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<MyFamilyListResponse> myFamilyListResponses) {
                list.clear();
                list.addAll(myFamilyListResponses);
                adapter.notifyDataSetChanged();
            }


            @Override
            public void onError(Throwable e) {
                refreshLayout.finishRefresh(false);
                ToastUtil.onError(MyFamilyActivity.this, e);

            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }


    /**
     * 绑卡弹框
     *
     * @time 2020/11/19 13:14
     */
    private void showChooseDialog() {
        mChooseDialog = ChooseDialog.newInstance();
        mChooseDialog.show(getSupportFragmentManager(), "mFinishDialog");
        mChooseDialog.setText("是否想要绑定自费就诊卡/医保卡", "绑卡", "暂不绑卡");
        mChooseDialog.setmListener(new ChooseDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                getYSGCardInfo();
            }

            @Override
            public void onCancel() {
            }
        });
    }

    private void showChooseDialog2(final String phone) {
        mChooseDialog = ChooseDialog.newInstance();
        mChooseDialog.show(getSupportFragmentManager(), "mFinishDialog");
        mChooseDialog.setText("您在温州和平国际医院曾创建过卡号，请关联绑定", "绑卡", "暂不绑卡");
        mChooseDialog.setmListener(new ChooseDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                showCodeDialog(phone, 0);
            }

            @Override
            public void onCancel() {
            }
        });
    }
    
    private void showChooseDialog3(final String phone) {
        mChooseDialog = ChooseDialog.newInstance();
        mChooseDialog.show(getSupportFragmentManager(), "mFinishDialog");
        mChooseDialog.setText("是否在医院里新建自费就诊卡", "新建", "暂不新建");
        mChooseDialog.setmListener(new ChooseDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                showCodeDialog(phone, 2);
            }

            @Override
            public void onCancel() {
            }
        });
    }


    private void getYSGCardInfo() {
        RestProxy.getInstance().getYSGCardInfo(myFamily.patientId, new BaseObserver<YSGCardInfoResponse>() {
            @Override
            public void onSuccess(YSGCardInfoResponse ysgCardInfoResponse) {
                if (ysgCardInfoResponse.operationType == 0) {//曾经创建过卡号
                    showChooseDialog2(ysgCardInfoResponse.phone);
                } else if (ysgCardInfoResponse.operationType == 1) {
                    //手机号不一致，可以直接发送验证码或者去修改手机号
                    showChangeCodeDialog(ysgCardInfoResponse.hosPhoneNo);
                } else if (ysgCardInfoResponse.operationType == 2) {
                    showChooseDialog3(ysgCardInfoResponse.phone);
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(MyFamilyActivity.this, e);
            }
        });
    }


    /**
     * 手机号一致，直接发送验证码
     *
     * @time 2020/11/19 14:17
     */
    private void showCodeDialog(String phone, final int type) {
        CodeDialog mCodeDialog = CodeDialog.newInstance();
        mCodeDialog.show(getSupportFragmentManager(), "mCodeDialog");
        mCodeDialog.setText(phone);
        mCodeDialog.setmListener(new CodeDialog.OnItemClickListener() {

            @Override
            public void onConfirm(String code) {
                if (type == 0) {
                    bindCard(code, phone);
                } else if (type == 2) {
                    createCard(code);
                }
            }

            @Override
            public void onCancel() {
                finish();
            }
        });
    }


    /**
     * 手机号不一致，发送验证码或者去修改手机号
     *
     * @time 2020/11/19 14:17
     */
    private void showChangeCodeDialog(String phone) {
        mChangeCodeDialog = CodeChangeDialog.newInstance(myFamily.patientId, myFamily.id, phone);
        mChangeCodeDialog.show(getSupportFragmentManager(), "mCodeDialog");
//        mChangeCodeDialog.setPhone( phone );
        mChangeCodeDialog.setmListener(new CodeChangeDialog.OnItemClickListener() {

            @Override
            public void onConfirm(String code) {
                bindCard(code, phone);
            }

            @Override
            public void onCancel() {
                finish();
            }
        });
    }

    private void bindCard(String code, String hosPhoneNo) {
        RestProxy.getInstance().bindCard(myFamily.patientId, code, hosPhoneNo, new BaseObserver<String>() {
            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(MyFamilyActivity.this, e);
            }

            @Override
            public void onSuccess(String result) {
                getFamilyList();
                ToastUtil.showToast(mContext, "绑定成功");
            }
        });
    }

    private void createCard(String code) {
        RestProxy.getInstance().createCard(myFamily.patientId, code, new BaseObserver<String>() {
            @Override
            public void onSuccess(String result) {
                getFamilyList();
                ToastUtil.showToast(mContext, "新增成功");
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(MyFamilyActivity.this, e);
            }
        });
    }

    public void startPayActivity() {
        Intent mIntent = new Intent(MyFamilyActivity.this, PayActivity.class);
        mIntent.putExtra(UIConstants.OBJ_MyFamilyListResponse, myFamily);
        mIntent.putExtra(UIConstants.OBJ_Doctor, doctor);
        mIntent.putExtra(UIConstants.CANNOT_SELECT_PATIENT, true);
        mIntent.putExtra(UIConstants.GRAPHIC_TYPE_FLAG, UIConstants.GRAPHIC_TYPE_2);
        startActivity(mIntent);
        finish();
    }

    public String getPatientId() {
        return myFamily.patientId;
    }
}
